package com.zglc.ms.shop.dao;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.zglc.ms.shop.model.UserInfo;

@Repository
public class UserDao {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private JdbcTemplate jdbcTemplate;

	public Integer getUserLevel(int userId) {
		final String sql = "SELECT user_level FROM user_level WHERE user_id = ? LIMIT 1";
		try {
			Integer level = jdbcTemplate.queryForObject(sql, new Object[] { userId }, Integer.class);
			return level == null ? 0 : level;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return 0;
		}
	}

	public UserInfo getUserInfo(int userId) {
		final String sql = " SELECT ui.phone, ui.head_img_url, ul.user_level, pu.available_point, up.is_auto_bid, "
				+ " up.is_open_account FROM user_info ui "
				+ " LEFT JOIN user_level ul ON  ul.user_id = ui.id "
				+ " LEFT JOIN point_user pu ON  pu.user_id = ui.id "
				+ " LEFT JOIN user_profile up ON  up.user_id = ui.id "
				+ " WHERE ui.id = ? ";
		try {
			return jdbcTemplate.queryForObject(sql, new Object[] { userId }, (rs, rowNum) -> {
				UserInfo userInfo = new UserInfo();
				userInfo.setAvailablePoint(rs.getInt("available_point"));
				userInfo.setHeadImgUrl(rs.getString("head_img_url"));
				userInfo.setPhone(rs.getString("phone"));
				userInfo.setUserLevel(rs.getInt("user_level"));
				userInfo.setAutoBidPlan(rs.getBoolean("is_auto_bid"));
				userInfo.setOpenAccount(rs.getBoolean("is_open_account"));
				return userInfo;
			});
		} catch (Exception e) {
			logger.error(e.getMessage());
			return null;
		}
	}

	public Map<Integer, String> getUserLevelMap() {
		final String sql = "SELECT level, level_describe FROM user_level_config";
		Map<Integer, String> map = new HashMap<>();
		jdbcTemplate.query(sql, (rs, rowNum) -> {
			map.put(rs.getInt("level"), rs.getString("level_describe"));
			return null;
		});
		
		return map;
	}

}